package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.BannerResource;
import com.eportal.domain.BannerStrategy;
import com.eportal.domain.DistributeLog;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.exception.JdbcException;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.BannerResourceService;
import com.eportal.service.BannerStrategyService;
import com.eportal.service.DistributeLogService;
import com.eportal.service.TCommunityService;
import com.eportal.util.ValidateUtil;

@Service("bannerStrategyService")
public class BannerStrategyServiceImpl  implements BannerStrategyService {

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(BannerStrategyServiceImpl.class.getName());
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
	private BannerResourceService bannerResourceService;
	@Autowired
	private DistributeLogService distributeLogService;
	@Autowired
    private TCommunityService tCommunityService;
	
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	
	public BannerStrategy add(BannerStrategy bannerStrategy) throws Exception {
    	dao.save(bannerStrategy);
        return bannerStrategy;
    }
	
    @Override
    public void update(BannerStrategy bannerStrategy) throws JdbcException {
      dao.update(bannerStrategy);
    }


    @Override
    public BannerStrategy get(Long sid) {
        return (BannerStrategy)  dao.getById(BannerStrategy.class, sid);
    }


    /**
     * 平台查询分配信息
     */
	@Override
	public Map<String, Object> getBySql(long shid,String distributeType) {
		List<Map<String, Object>> list= null;
		Map<String, Object> map = null;
		StringBuilder sql = new StringBuilder("select a.* from (select t.*,s.sid as shelvesid,s.dtype,s.agtcode as agt,s.cName,s.type,sy.uname as cuser1,s.ctime as ctime1,s.curl,s.settlementMethod,s.expectedIncome,s.adDetails   from banner_strategy t right join banner_resource s on t.shid=s.sid left join sysopt sy on s.cuser=sy.sid where s.sid=");
		sql.append(shid);
		sql.append(") a where a.enabledflag is null or a.enabledflag=1");
		list= dao.queryBySql(sql.toString());
		if (list.size()>0) {
			map = list.get(0);
			map = getdistribute(shid,map);
		}
		if("2".equals(distributeType)){//下架，追加上从communityId中查出来的agtCode
			List<Map<String, Object>> list3 = getAppendAgt(map.get("sid"));
			StringBuffer sbAgt = new StringBuffer();
			if(list3 != null && list3.size()>0){
				for (Map<String, Object> map3 : list3) {
					if (sbAgt.length()!=0) {
						sbAgt.append(",");
					}
					sbAgt.append(map3.get("agtcode"));
				}
			}
			if (sbAgt.length()!=0) {
				map.put("appendAgt", sbAgt.toString());
			}
    	}
		return map;
	}
	//追加上从communityId中查出来的agtCode
	private List<Map<String, Object>> getAppendAgt(Object sid) {
		String sqlAppendAgt = "select c.*,a.agtname from(select c.agtcode from t03_community c where c.sid in "
				+ "(select cm.sid from T03_COMMUNITY cm where instr((select ts.communityid from BANNER_STRATEGY ts where ts.sid="+sid+"), ','||cm.sid||',') > 0)  "
				+ "group by c.agtcode)c left join t02_agtent a on c.agtcode=a.agtcode";
		List<Map<String, Object>> list3 = dao.queryBySql(sqlAppendAgt);
		return list3;
	}
	

	@Override
	@LogAnnotation(operateDescribe="广告资源分配")  
	public Map<String, Object> updateMethod(BannerStrategy bannerStrategy) {
		 String msg = ValidateUtil.validate(bannerStrategy);
    	 
         if (msg == null || msg.trim().length() == 0) {
             try {
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	int userRole =  (Integer) getSession().getAttribute("userRole");
            	//策略分配记录到操作日志
            	DistributeLog distributeLog = new DistributeLog();
            	distributeLog.setcTime(new Timestamp(System.currentTimeMillis()));
            	distributeLog.setcUser(Long.toString(user.getSid()));
            	distributeLog.setLogType("1");
            	distributeLog.setRange(bannerStrategy.getRange());
            	distributeLog.setType("0");
            	BannerResource bannerResource = bannerResourceService.get(bannerStrategy.getShid());
        		//新增
            	if (bannerStrategy.getSid()==null) {
            		bannerStrategy.setBannerPosition(","+bannerStrategy.getBannerPosition().trim().replace(" ", "")+",");
            		bannerStrategy.setcUser(Long.toString(user.getSid()));
            		bannerStrategy.setcTime(new Timestamp(System.currentTimeMillis()));
            		bannerStrategy.setEnabledflag(1);
            		if(bannerStrategy.getRange() ==BannerStrategy.RANGEAGTCODE && StringUtils.isNotBlank(bannerStrategy.getAgtCode())){//合作方下全部小区
            			bannerStrategy.setAgtCode(","+bannerStrategy.getAgtCode().trim().replace(" ", "")+",");
            			distributeLog.setAgtCode(bannerStrategy.getAgtCode());
            			bannerStrategy.setCommunityId("");
            			String communityIds = getCommunityId(bannerStrategy.getAgtCode().trim().replace(" ", ""));
            			//日志
            			distributeLog.setCommunityId(communityIds);
            		}else if(StringUtils.isNotBlank(bannerStrategy.getCommunityId())){
            			bannerStrategy.setAgtCode("");
            			bannerStrategy.setCommunityId(","+bannerStrategy.getCommunityId().trim().replace(" ", "")+",");
        				//日志
        				distributeLog.setCommunityId(bannerStrategy.getCommunityId().trim().replace(" ", ""));
            		}
            		add(bannerStrategy);
				}else{//修改
					BannerStrategy entity = get(bannerStrategy.getSid());
					entity.setEnabledflag(1);
					if (user.getAgtCode().equals(bannerResource.getAgtCode()) || userRole == 1 || userRole == 2) {
						entity.setBannerPosition(","+bannerStrategy.getBannerPosition().trim().replace(" ", "")+",");
						entity.setPriority(bannerStrategy.getPriority());
						entity.setTimeFrom(bannerStrategy.getTimeFrom());
						entity.setTimeTo(bannerStrategy.getTimeTo());
					}
					entity.setRange(bannerStrategy.getRange());
            		if(bannerStrategy.getRange() ==BannerStrategy.RANGEAGTCODE){//合作方下全部小区
            			if(StringUtils.isBlank(bannerStrategy.getAgtCode())){
        					result.put("code", 1);
            	  	        result.put("msg", "操作成功");
            	  	        return result;
        				}else{
        					//agtCode增加
        					String agtcodeSB = getNoRepeat(bannerStrategy.getAgtCode(),entity.getAgtCode());
        					if(StringUtils.isNotBlank(entity.getAgtCode()) && StringUtils.isNotBlank(agtcodeSB)){
        						entity.setAgtCode(entity.getAgtCode()+agtcodeSB);
        					}else{
        						entity.setAgtCode(agtcodeSB);
        					}		
        					distributeLog.setAgtCode(entity.getAgtCode());
        					//如果有所属的communityId,则去掉
        					String communityIds = getCommunityId(bannerStrategy.getAgtCode().trim().replace(" ", ""));
        					
        					String communityIdSB =  offNoRepeat(communityIds,entity.getCommunityId());
        					entity.setCommunityId(communityIdSB);
//        					//日志
//        					distributeLog.setCommunityId(communityIdSB);
        				
        					
        				}
            		}else{//单合作方下小区
            			if(StringUtils.isBlank(bannerStrategy.getAgtCode()) || StringUtils.isBlank(bannerStrategy.getCommunityId())){
        					result.put("code", 1);
            	  	        result.put("msg", "操作成功");
            	  	        return result;
            			}else{
        					String communityIdSB =  getNoRepeat(bannerStrategy.getCommunityId(),entity.getCommunityId());
        					if(StringUtils.isBlank(entity.getCommunityId())){
        						entity.setCommunityId(communityIdSB);
        					}else if (StringUtils.isNotBlank(communityIdSB)) {
        						entity.setCommunityId(entity.getCommunityId()+communityIdSB);
        					}
        					//日志
        					distributeLog.setCommunityId(bannerStrategy.getCommunityId());
        				}
            		}
					update(entity);
				}
            	distributeLog.setResourcesId(Long.toString(bannerStrategy.getShid()));
            	distributeLogService.save(distributeLog);
            	
            	if (bannerResource.getIsOnLine() !=2) {
            		 bannerResource.setIsOnLine(2);
            		 bannerResourceService.update(bannerResource);
				}
            	 result.put("objectId", bannerStrategy.getSid());
            	 result.put("code", 1);
                 result.put("msg", "操作成功");
             } catch (Exception e) {
                 log.error("广告资源分配失败", e);
                 throw new MdKnownRunTimeException("广告资源分配失败");
             }
         } else {
             result.put("code", 0);
             result.put("msg", msg);
         }
         return result;
	}

	/**
	 * 
	 * @param str1 现在要上架的字符串
	 * @param str2 已上架的字符串
	 * @return
	 */
	private String getNoRepeat(String str1, String str2) {
		if(StringUtils.isBlank(str1)){
			return str2;
		}
		StringBuffer sb = new StringBuffer("");
		if(StringUtils.isBlank(str2)){
			sb.append(",");
			sb.append(str1.trim().replace(" ", ""));
			sb.append(",");
			return sb.toString();
		}
		String[] agtcodes = str1.trim().replace(" ", "").split(",");
		for (String string : agtcodes) {
			if (str2.indexOf(","+string+",") ==-1) {
				sb.append(string);
				sb.append(",");
			}
		}
		return sb.toString();
	}

	/**
	 * 通过agtcode获取CommunityId
	 * @param agtCodes
	 * @return
	 */
	public String getCommunityId(String agtCodes) {
		List<String> listArr = new ArrayList<String>(); 
		StringBuffer communitys = new StringBuffer("");
		List<TCommunity> tcommunitys = new ArrayList<TCommunity>();
    	listArr = Arrays.asList(agtCodes.split(","));
    	String sql = "from TCommunity where agtCode in (:ids)";
    	tcommunitys = dao.executeFindS(sql,"ids",listArr);
    	if (tcommunitys != null) {
    		for (TCommunity tCommunity : tcommunitys) {
    			if (!"".equals(communitys.toString())) {
    				communitys.append(",");
    			}
    			communitys.append(tCommunity.getSid());
			}
    		return communitys.toString();
		}
		return null;
	}
	@Override
	@LogAnnotation(operateDescribe="锁厂广告资源下架") 
	public Map<String, Object> offLockBannerMethod(String sid) {
		try {
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	//策略分配记录到操作日志
    	DistributeLog distributeLog = new DistributeLog();
    	distributeLog.setcTime(new Timestamp(System.currentTimeMillis()));
    	distributeLog.setcUser(Long.toString(user.getSid()));
    	distributeLog.setLogType("1");
    	distributeLog.setRange(1);
    	distributeLog.setType("1");
    	distributeLog.setResourcesId(sid);
    	distributeLog.setAgtCode("*");
    	distributeLog.setCommunityId("*");
    	
    	//分配策略
    	StringBuffer sb = new StringBuffer("from BannerStrategy where shid=");
 		sb.append(sid);
 		BannerStrategy entity = (BannerStrategy) dao.loadObject(sb.toString());
    	entity.setEnabledflag(0);
		updateBannerResource(Long.parseLong(sid),0);
		update(entity);
		distributeLogService.save(distributeLog);
    	result.put("objectId", sid);
        result.put("code", 1);
        result.put("msg", "操作成功");
		} catch (Exception e) {
            log.error("广告资源下架失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
		return result;
	}
	@Override
	@LogAnnotation(operateDescribe="广告资源下架") 
	public Map<String, Object> offMethod(BannerStrategy bannerStrategy, String agtName, String comuName, String offType) {
		try {
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	//策略分配记录到操作日志
        	DistributeLog distributeLog = new DistributeLog();
        	distributeLog.setcTime(new Timestamp(System.currentTimeMillis()));
        	distributeLog.setcUser(Long.toString(user.getSid()));
        	distributeLog.setLogType("1");
        	distributeLog.setRange(bannerStrategy.getRange());
        	distributeLog.setType("1");
        	distributeLog.setResourcesId(Long.toString(bannerStrategy.getShid()));
        	
     		
			BannerStrategy entity = get(bannerStrategy.getSid());
			if( "all".equals(offType)){//全局。已下架整个资源
				entity.setEnabledflag(0);
				updateBannerResource(bannerStrategy.getShid(),0);
				//日志
				distributeLog.setAgtCode("*");
				distributeLog.setCommunityId("*");
    		}else if(bannerStrategy.getRange() ==bannerStrategy.RANGEAGTCODE){//合作方下全部小区
    			if(StringUtils.isBlank(bannerStrategy.getAgtCode())){//没有要下架的合作方
    				result.put("code", 1);
    	  	        result.put("msg", "操作成功");
    	  	        return result;
    			}
    			if(StringUtils.isNotBlank(entity.getAgtCode())){
    				String nowAgtCodes = offNoRepeat(bannerStrategy.getAgtCode(),entity.getAgtCode());
    				entity.setAgtCode(nowAgtCodes);
    			}
    			String agtcodes = bannerStrategy.getAgtCode().trim().replace(" ", "");
    			//如果上架的小区中含有，则去除
    			String communityIds = getCommunityId(agtcodes);
    			if(StringUtils.isNotBlank(entity.getCommunityId())){
    				String nowCommunityIds = offNoRepeat(communityIds,entity.getCommunityId());
    				entity.setCommunityId(nowCommunityIds);
    			}
    			//日志
    			distributeLog.setAgtCode(agtcodes);
    		}else{
    			if(StringUtils.isBlank(bannerStrategy.getAgtCode()) || StringUtils.isBlank(bannerStrategy.getCommunityId())){
    				result.put("code", 1);
    	  	        result.put("msg", "操作成功");
    	  	        return result;
    			}
    			//如果是以前全部上架的，去除agtCode
    			String nowAgtCodes = null;
    			if(StringUtils.isNotBlank(entity.getAgtCode())){
    				nowAgtCodes = offNoRepeat(bannerStrategy.getAgtCode(),entity.getAgtCode());
    			}
    			String type="normal";//正常流程下架，comunityId包含
    			if (entity.getAgtCode() != null && !entity.getAgtCode().equals(nowAgtCodes)) {
    				type="abnormal";//comunityId不包含，需要新增合作方下其他社区到comunityId
    			}
    			entity.setAgtCode(nowAgtCodes);
    			String agtcodes = bannerStrategy.getAgtCode().trim().replace(" ", "");
    			String nowCommunityIds = null;
    			if("normal".equals(type)){
    				//coumunityId有则去除。
    				nowCommunityIds = offNoRepeat(bannerStrategy.getCommunityId(),entity.getCommunityId());
    			}else{
    				//上架本合作方下除了要下架的coumunityId之外的coumunityId
    				String communityIds = getCommunityId(agtcodes);
    				String ifLeaveCommunityIds = offNoRepeat(bannerStrategy.getCommunityId(),","+communityIds+",");
    				if(StringUtils.isNotBlank(ifLeaveCommunityIds) && StringUtils.isNotBlank(entity.getCommunityId())){
    					nowCommunityIds = entity.getCommunityId()+ifLeaveCommunityIds.substring(1);
    				}else if(StringUtils.isBlank(ifLeaveCommunityIds)){
    					nowCommunityIds = entity.getCommunityId();
    				}else{
    					nowCommunityIds =ifLeaveCommunityIds;
    				}
    			}
    			entity.setCommunityId(nowCommunityIds);
    			//日志
    			distributeLog.setCommunityId(bannerStrategy.getCommunityId().trim().replace(" ", ""));
    		}
			update(entity);
			distributeLogService.save(distributeLog);
        	result.put("objectId", bannerStrategy.getSid());
            result.put("code", 1);
            result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("广告资源下架失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
		return result;
	}

		/**
	 * 去除要下架的字符串。留下的是已上架的
	 * @param str1 传过来的要下架的字符串
	 * @param str2 原先的已上架的字符串
	 * @return
	 */
	private String offNoRepeat(String str1, String str2) {
		if (StringUtils.isBlank(str1)) {
			return str2;
		}
		if(StringUtils.isBlank(str2)){
			return "";
		}
		String allStr1 = ","+str1.trim().replace(" ", "")+",";
		String beforeAgtcodes = str2.substring(1,str2.length()-1);
		String[] beforeArr = beforeAgtcodes.split(",");
		StringBuffer sb = new StringBuffer("");
		for (String stringA : beforeArr) {
			if (allStr1.indexOf(","+stringA+",")==-1) {
				if (sb.length()==0) {
					sb.append(",");
				}
				sb.append(stringA);
				sb.append(",");
			}
		}
		return sb.toString();
	}
	/**
	 * 修改资源
	 * @param shid
	 * @param isOnLine
	 */
	private Map<String, Object> updateBannerResource(Long shid, int isOnLine) {
		try {
			BannerResource bannerResource = bannerResourceService.get(shid);
			bannerResource.setIsOnLine(isOnLine);
			bannerResourceService.update(bannerResource);
			result.put("code", 1);
			result.put("msg", "操作成功");
		} catch (Exception e) {
			 result.put("code", 0);
             result.put("msg", "操作失败");
             log.error(this, e);
		}
    	return result;
	}

	@Override
	public Map<String, Object> reports(long shid) {
		Map<String, Object> map = null;
		final List<String> tmp2 = new LinkedList<String>();
		StringBuffer sb = new StringBuffer("select t.sid,t.range,t.agtcode,t.communityid,sy.uname as cuser,to_char(s.ctime,'yyyy-MM-dd HH24:mi:ss') as ctime  from banner_strategy t "
				+ "right join banner_resource s on t.shid=s.sid left join sysopt sy on s.cuser=sy.sid where t.shid='");
		sb.append(shid);
		sb.append("'");
		List<Map<String, Object>> list= null;
		
		list= dao.queryBySql(sb.toString());
		if (list.size()<1) {
			map = new HashMap<String, Object>();
			map.put("agt", "无");
			map.put("comu", "无");
			map.put("people", "无");
			map.put("cUser", "无");
			map.put("cTime", "无");
			map.put("distribute", "无");
			
			return map;
		}
		map = list.get(0);
		map = getdistribute(shid,map);
		
		int userRole =  (Integer) getSession().getAttribute("userRole");
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
		
		StringBuffer countsql = new StringBuffer("select count(sid) from banner_click t where t.resource_id=");
		countsql.append(shid);
		map.put("clickNum", 0);
		if (userRole == 3 || userRole == 4) {
			if(map.get("agtDistribute") == null && map.get("agtHaveDistribute") == null){
				map.put("agt", 0);
				map.put("comu", 0);
				map.put("people", 0);
				return map;
			}else if(map.get("agtDistribute") != null){//合作方下全部小区
				map.put("agt", 1);
				List<TCommunity> listComu = tCommunityService.listByAgtCodes(user.getAgtCode());
				if (listComu == null || listComu.size()<=0) {
					map.put("comu", 0);
					map.put("people", 0);
					return map;
				}else{
					map.put("comu", listComu.size());
					for (TCommunity tCommunity : listComu) {
						tmp2.add(Long.toString(tCommunity.getSid()));
					}
				}
			}else{//合作方下部分小区
				map.put("agt", 1);
				String comuIds =  (String) map.get("agtHaveDistribute");
				String[] comuIdsArr = comuIds.split(",");
				map.put("comu", comuIdsArr.length);
				for (String cid : comuIdsArr) {
					tmp2.add(cid);
				}
			}
			countsql.append(" and t.agtcode='");
			countsql.append(user.getAgtCode());
			countsql.append("'");
		}else{//平台管理
			String agtCodes = (String) map.get("AGTCODE");
			List<Map<String, Object>> listAgtAndComu = getAppendAgtAndComu(map.get("sid"));
			HashSet<String> set =new HashSet<String>();
			if (listAgtAndComu.size()>0) {
				for (Map<String, Object> map2 : listAgtAndComu) {
					set.add(map2.get("AGTCODE").toString());
					tmp2.add(map2.get("sid").toString());
				}
			}
			if (StringUtils.isBlank(agtCodes)){//无公司上架全部社区
				if(listAgtAndComu.size()<=0){//无追加
					map.put("agt", 0);
					map.put("comu", 0);
					map.put("people", 0);
					return map;
				}else{//追加上的
					map.put("agt", set.size());
					map.put("comu", tmp2.size());
				}
			}else{//有公司上架全部社区
				String[] arrAgtCode = agtCodes.split(",");
				if(listAgtAndComu.size()<=0){//无追加
					map.put("agt", arrAgtCode.length-1);
				}else{//追加上的
					map.put("agt", arrAgtCode.length-1+set.size());
				}
				
				List<String> tmpAgtCode = Arrays.asList(arrAgtCode);
				String comusql = "select sid from TCommunity where  agtCode in (:ids)";
				List<Long> listComu = dao.executeFindS(comusql,"ids",tmpAgtCode);
				for (Long sid : listComu) {
					tmp2.add(Long.toString(sid));
				}
				map.put("comu", tmp2.size());
			}
			
		}
		int count = dao.count(countsql.toString());
		map.put("clickNum", count);
		
		if (tmp2.size()>0) {
			String comusql = "select count(sid) as coun from UsersCommunity where status=1 and communityId in (:ids)";
			List<String> listUC = dao.executeFindS(comusql,"ids",tmp2);
			if (listUC.size()>0) {
				map.put("people", listUC.get(0));
			}else{
				map.put("people", 0);
			}
		}else{
			map.put("people", 0);
			return map;
		}
		
		return map;
	}
	
	//追加上从communityId中查出来的agtCode
		private List<Map<String, Object>> getAppendAgtAndComu(Object sid) {
			String sqlAppendAgt = "select cm.sid,cm.agtcode from T03_COMMUNITY cm where instr((select ts.communityid from BANNER_STRATEGY ts where ts.sid="+sid+"), ','||cm.sid||',') > 0 ";
			List<Map<String, Object>> list3 = dao.queryBySql(sqlAppendAgt);
			return list3;
		}
	private Map<String, Object> getdistribute(long shid, Map<String, Object> map) {
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
		int userRole =  (Integer) getSession().getAttribute("userRole");
		//分配信息
		StringBuffer sb = new StringBuffer("select t.type,to_char(t.ctime,'yyyy-mm-dd HH24:mi:ss') as ctime,s.uname  "
				+ "from DISTRIBUTELOG t "
				+ "left join sysopt s on t.cuser=s.sid where t.logType='1' and t.resourcesid='");
		sb.append(shid);
		sb.append("' order by t.sid desc");
		List<Map<String, String>> distributeMap = dao.queryBySql(sb.toString());
		if (distributeMap != null && distributeMap.size()>0) {
			StringBuffer distribute = new StringBuffer();
			StringBuffer off = new StringBuffer();
			for (Map<String, String> map2 : distributeMap) {
				if ("0".equals(map2.get("type"))) {
					distribute.append("操作者：");
					distribute.append(map2.get("uname"));
					distribute.append(", 操作时间：");
					distribute.append(map2.get("ctime"));
					distribute.append(";\r\n");
				}else{
					off.append("操作者：");
					off.append(map2.get("uname"));
					off.append(", 操作时间：");
					off.append(map2.get("ctime"));
					off.append(";\r\n");
				}
			}
			map.put("distribute", distribute.toString());
			map.put("off", off.toString());
		}
		
		String agt = (String) map.get("agtCode");
		String[] agtCodeIds = null;
		if(StringUtils.isNotBlank(agt)){
			if (userRole == 1 || userRole == 2 || userRole == 21) {
				agtCodeIds = agt.substring(1,agt.length()-1).split(",");
			}
			if (userRole == 3 || userRole == 4) {
				if (agt.indexOf(","+user.getAgtCode()+",")>-1) {
					agtCodeIds=new String[]{user.getAgtCode()};
				}
			}
		}
		map.put("agtDistribute",agtCodeIds);
		//合作方信息
		StringBuffer distributeRange = new StringBuffer();
		if(agtCodeIds != null){
			distributeRange.append("上架全部小区:");
			List<String> listArr = Arrays.asList(agtCodeIds);
			String agtsql = "select agtName from TAgent where agtCode in (:agtCodeIds)";
			List<String> list1 = dao.executeFindS(agtsql,"agtCodeIds",listArr);
			if(list1 != null && list1.size()>0){
				distributeRange.append("\r\n");
				distributeRange.append("	公司：");
				distributeRange.append(list1.toString());
				map.put("distributeRange",distributeRange.toString());
			}
		}
		//社区信息
		String comu = (String) map.get("communityId");
		if(StringUtils.isBlank(comu)){
			return map;
		}
		if (userRole == 1 || userRole == 2 || userRole == 21) {
			String[] comuIds = comu.substring(1,comu.length()-1).split(",");
			final List<Long> tmp2 = new LinkedList<Long>();
			for (String s : comuIds) {
				tmp2.add(Long.parseLong(s));
			}
			String sql = "select c.*,a.agtname from(select c.agtcode,XMLAGG(XMLELEMENT(E, c.communityname || ',')).EXTRACT('//text()').getclobval() as comuName from t03_community c where c.sid in "
					+ "(select cm.sid from T03_COMMUNITY cm where instr((select ts.communityid from BANNER_STRATEGY ts where ts.sid="+map.get("sid")+"), ','||cm.sid||',') > 0)  "
					+ "group by c.agtcode)c left join t02_agtent a on c.agtcode=a.agtcode";
			List<Map<String, Object>> list3 = dao.queryBySql(sql);
			if(list3 != null && list3.size()>0){
				distributeRange.append("\r\n");
				distributeRange.append("上架部分小区:");
				for (Map<String, Object> map3 : list3) {
					distributeRange.append("\r\n");
					distributeRange.append("	公司：");
					distributeRange.append(map3.get("AGTNAME"));
					distributeRange.append("；	上架社区:");
					distributeRange.append(map3.get("COMUNAME"));
				}
			}
		}
		if (userRole == 3 || userRole == 4) {
			List<TCommunity> listComu = tCommunityService.listByAgtCodes(user.getAgtCode());
			if (listComu == null || listComu.size()<=0) {
				return map;
			}
			StringBuffer comuName = new StringBuffer("");
			StringBuffer comuids = new StringBuffer();
			for (TCommunity tCommunity : listComu) {
				String conuid = ","+tCommunity.getSid()+",";
				if (comu.indexOf(conuid)>-1) {
					comuName.append(tCommunity.getCommunityName());
					comuName.append(",");
					comuids.append(tCommunity.getSid());
					comuids.append(",");
				}
			}
			if(StringUtils.isNotBlank(comuName.toString())){
				distributeRange.append("\r\n");
				distributeRange.append("上架部分小区:");
				distributeRange.append(comuName.substring(0, comuName.length()-1));
				map.put("agtHaveDistribute",comuids.substring(0, comuids.length()-1));
			}
		}
		map.put("distributeRange",distributeRange.toString());
		
		return map;
		}

	
	}

